﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 车辆服务管理;
using 审批流引擎;
using Domain;
using PersonnelSystemManagement.人事管理;
using PersonnelSystemManagement.系统管理;
using Domain_nwj.ContractManagement;
using Domain_nwj.BasicInformation;
using Domainwj.物资管理;
using Domainwj.结算管理;

namespace Intarstructure
{
    /// <summary>
    /// 数据库上下文
    /// </summary>
    public class TMSDbContext : DbContext
    {
        private readonly DbContextOptions<TMSDbContext> options;

        /// <summary>
        /// 上下文配置
        /// </summary>
        /// <param name="options">数据</param>
        public TMSDbContext(DbContextOptions<TMSDbContext> options) : base(options)
        {
            this.options = options;
        }

        /// <summary>
        /// 配置模型创建
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 配置审计字段的默认值
            ConfigureAuditFields(modelBuilder);
            
            // 配置审批字段的默认值
            ConfigureApprovalFields(modelBuilder);
            
            // 配置表名映射
            ConfigureTableNames(modelBuilder);
            
            // 配置字段约束
            ConfigureFieldConstraints(modelBuilder);
        }
        #region 人事管理
        /// <summary>
        /// 部门信息
        /// </summary>
        public DbSet<Department> Departments { get; set; }
        /// <summary>
        /// 员工类别
        /// </summary>
        public DbSet<EmployeeCategory> EmployeeCategories { get; set; }
        /// <summary>
        /// 入职信息
        /// </summary>
        public DbSet<Onboarding> Onboardings { get; set; }
        /// <summary>
        /// 人员信息
        /// </summary>
        public DbSet<PersonInfo> PersonInfos { get; set; }
        /// <summary>
        /// 人员入职关联
        /// </summary>
        public DbSet<PersonInfoOnboarding> PersonInfoOnboardings { get; set; }
        /// <summary>
        /// 人员转正关联
        /// </summary>
        public DbSet<PersonInfoRegularized> PersonInfoRegularizeds { get; set; }
        /// <summary>
        /// 人员离职关联
        /// </summary>
        public DbSet<PersonInfoResign> PersonInfoResigns { get; set; }
        /// <summary>
        /// 职位信息
        /// </summary>
        public DbSet<Position> Positions { get; set; }
        /// <summary>
        /// 转正信息
        /// </summary>
        public DbSet<Regularized> Regularizeds { get; set; }
        /// <summary>
        /// 离职信息
        /// </summary>
        public DbSet<Resign> Resigns { get; set; }
        #endregion

        #region 合同管理
        /// <summary>
        /// 货主合同
        /// </summary>
        public DbSet<CargoOwnerContracts> CargoOwnerContracts { get; set; }
        /// <summary>
        /// 承运合同
        /// </summary>
        public DbSet<CarriageContracts> CarriageContracts { get; set; }
        /// <summary>
        /// 通用合同
        /// </summary>
        public DbSet<GeneralContracts> GeneralContracts { get; set; }
        #endregion

        #region 基础信息
        /// <summary>
        /// 货主信息
        /// </summary>
        public DbSet<CargoOwner> CargoOwners { get; set; }
        /// <summary>
        /// 外部合作单位
        /// </summary>
        public DbSet<ExternalCooperationUnits> ExternalCooperationUnits { get; set; }
        /// <summary>
        /// 燃油费用
        /// </summary>
        public DbSet<FuelExpenses> FuelExpenses { get; set; }
        /// <summary>
        /// 车辆管理
        /// </summary>
        public DbSet<VehicleManagement> VehicleManagements { get; set; }
        #endregion

        #region 审批流引擎
        /// <summary>
        /// 默认流程详情
        /// </summary>
        public DbSet<DefaultProcessDetail> DefaultProcessDetails { get; set; }
        /// <summary>
        /// 节点信息
        /// </summary>
        public DbSet<Nodes> Nodes { get; set; }
        /// <summary>
        /// 流程信息
        /// </summary>
        public DbSet<Process> Processes { get; set; }
        /// <summary>
        /// 流程详情
        /// </summary>
        public DbSet<ProcessDetail> ProcessDetails { get; set; }
        /// <summary>
        /// 审批记录
        /// </summary>
        public DbSet<Record> Records { get; set; }
        /// <summary>
        /// 类型信息
        /// </summary>
        public DbSet<Types> Types { get; set; }
        #endregion

        #region 物资管理
        /// <summary>
        /// 材质信息
        /// </summary>
        public DbSet<Material> Materials { get; set; }
        /// <summary>
        /// 物资统计
        /// </summary>
        public DbSet<MaterialStatistics> MaterialStatistics { get; set; }
        /// <summary>
        /// 物资领用
        /// </summary>
        public DbSet<MaterialWithdrawal> MaterialWithdrawals { get; set; }
        /// <summary>
        /// 物资采购
        /// </summary>
        public DbSet<SupplyPurchase> SupplyPurchases { get; set; }
        /// <summary>
        /// 物资类型信息
        /// </summary>
        public DbSet<Domainwj.物资管理.Type> MaterialTypes { get; set; }
        /// <summary>
        /// 仓库入库管理
        /// </summary>
        public DbSet<WarehouseReceivingManagement> WarehouseReceivingManagements { get; set; }
        #endregion

        #region 系统管理
        /// <summary>
        /// 公司信息
        /// </summary>
        public DbSet<CompanyInfo> CompanyInfos { get; set; }
        /// <summary>
        /// 菜单信息
        /// </summary>
        public DbSet<Menus> Menus { get; set; }
        /// <summary>
        /// 权限信息
        /// </summary>
        public DbSet<Permissions> Permissions { get; set; }
        /// <summary>
        /// 角色菜单关联
        /// </summary>
        public DbSet<RoleMenus> RoleMenus { get; set; }
        /// <summary>
        /// 角色权限关联
        /// </summary>
        public DbSet<RolePermissions> RolePermissions { get; set; }
        /// <summary>
        /// 角色信息
        /// </summary>
        public DbSet<Roles> Roles { get; set; }
        /// <summary>
        /// 用户角色关联
        /// </summary>
        public DbSet<UserRoles> UserRoles { get; set; }
        /// <summary>
        /// 用户信息
        /// </summary>
        public DbSet<Users> Users { get; set; }
        #endregion

        #region 结算管理
        /// <summary>
        /// 进销项发票管理
        /// </summary>
        public DbSet<InboundOutboundInvoiceManagement> InboundOutboundInvoiceManagements { get; set; }
        /// <summary>
        /// 付款管理
        /// </summary>
        public DbSet<PaymentManagemen> PaymentManagemens { get; set; }
        /// <summary>
        /// 应收费用管理
        /// </summary>
        public DbSet<ReceivableFeeManagement> ReceivableFeeManagements { get; set; }
        #endregion

        #region 车辆服务管理
        /// <summary>
        /// 事故记录
        /// </summary>
        public DbSet<AccidentRecord> AccidentRecords { get; set; }
        /// <summary>
        /// 违章记录
        /// </summary>
        public DbSet<BreakRulesAndRegulations> BreakRulesAndRegulations { get; set; }
        /// <summary>
        /// 费用记录
        /// </summary>
        public DbSet<FeeRecord> FeeRecords { get; set; }
        /// <summary>
        /// 保养记录
        /// </summary>
        public DbSet<MaintainRecord> MaintainRecords { get; set; }
        /// <summary>
        /// 维修记录
        /// </summary>
        public DbSet<RepairRecord> RepairRecords { get; set; }
        /// <summary>
        /// 轮胎记录
        /// </summary>
        public DbSet<TireRecord> TireRecords { get; set; }
        #endregion

        #region 追踪管理
        /// <summary>
        /// 订单信息
        /// </summary>
        public DbSet<Order_info> Order_infos { get; set; }
        /// <summary>
        /// 路线信息
        /// </summary>
        public DbSet<Route_info> Route_infos { get; set; }
        /// <summary>
        /// 运输状态日志
        /// </summary>
        public DbSet<Shipping_status_log> Shipping_status_logs { get; set; }
        #endregion

        #region 配置方法

        /// <summary>
        /// 配置审计字段
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        private void ConfigureAuditFields(ModelBuilder modelBuilder)
        {
            // 配置所有继承 AuditableEntityBase 的实体
            foreach (var entityType in modelBuilder.Model.GetEntityTypes()
                .Where(e => typeof(Domain.审计字段.AuditableEntityBase).IsAssignableFrom(e.ClrType)))
            {
                // 配置创建时间默认值
                modelBuilder.Entity(entityType.ClrType)
                    .Property(nameof(Domain.审计字段.AuditableEntityBase.CreatedAt))
                    .HasDefaultValueSql("NOW(6)"); // MySQL 6位微秒精度
                
                // 配置软删除默认值
                modelBuilder.Entity(entityType.ClrType)
                    .Property(nameof(Domain.审计字段.AuditableEntityBase.IsDeleted))
                    .HasDefaultValue(false);
                
                // 配置创建时间字段类型
                modelBuilder.Entity(entityType.ClrType)
                    .Property(nameof(Domain.审计字段.AuditableEntityBase.CreatedAt))
                    .HasColumnType("datetime(6)");
                
                // 配置修改时间字段类型
                modelBuilder.Entity(entityType.ClrType)
                    .Property(nameof(Domain.审计字段.AuditableEntityBase.LastModifiedAt))
                    .HasColumnType("datetime(6)");
            }
        }

        /// <summary>
        /// 配置审批字段
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        private void ConfigureApprovalFields(ModelBuilder modelBuilder)
        {
            // 配置所有继承 ApprovalAuditableEntityBase 的实体
            foreach (var entityType in modelBuilder.Model.GetEntityTypes()
                .Where(e => typeof(Domain.审计字段.ApprovalAuditableEntityBase).IsAssignableFrom(e.ClrType)))
            {
                // 配置审批状态默认值
                modelBuilder.Entity(entityType.ClrType)
                    .Property(nameof(Domain.审计字段.ApprovalAuditableEntityBase.ApprovalStatus))
                    .HasDefaultValue(0);
                
                // 配置审批时间字段类型
                modelBuilder.Entity(entityType.ClrType)
                    .Property(nameof(Domain.审计字段.ApprovalAuditableEntityBase.ApprovalTime))
                    .HasColumnType("datetime(6)");
                
                // 配置提交时间字段类型
                modelBuilder.Entity(entityType.ClrType)
                    .Property(nameof(Domain.审计字段.ApprovalAuditableEntityBase.SubmittedTime))
                    .HasColumnType("datetime(6)");
                
                // 配置撤回时间字段类型
                modelBuilder.Entity(entityType.ClrType)
                    .Property(nameof(Domain.审计字段.ApprovalAuditableEntityBase.WithdrawnTime))
                    .HasColumnType("datetime(6)");
            }
        }

        /// <summary>
        /// 配置表名映射
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        private void ConfigureTableNames(ModelBuilder modelBuilder)
        {
            // 人事管理模块
            modelBuilder.Entity<Department>().ToTable("department");
            modelBuilder.Entity<EmployeeCategory>().ToTable("employee_category");
            modelBuilder.Entity<Onboarding>().ToTable("onboarding");
            modelBuilder.Entity<PersonInfo>().ToTable("person_info");
            modelBuilder.Entity<PersonInfoOnboarding>().ToTable("person_info_onboarding");
            modelBuilder.Entity<PersonInfoRegularized>().ToTable("person_info_regularized");
            modelBuilder.Entity<PersonInfoResign>().ToTable("person_info_resign");
            modelBuilder.Entity<Position>().ToTable("position");
            modelBuilder.Entity<Regularized>().ToTable("regularized");
            modelBuilder.Entity<Resign>().ToTable("resign");

            // 合同管理模块
            modelBuilder.Entity<CargoOwnerContracts>().ToTable("cargo_owner_contracts");
            modelBuilder.Entity<CarriageContracts>().ToTable("carriage_contracts");
            modelBuilder.Entity<GeneralContracts>().ToTable("general_contracts");

            // 基础信息模块
            modelBuilder.Entity<CargoOwner>().ToTable("cargo_owner");
            modelBuilder.Entity<ExternalCooperationUnits>().ToTable("external_cooperation_units");
            modelBuilder.Entity<FuelExpenses>().ToTable("fuel_expenses");
            modelBuilder.Entity<VehicleManagement>().ToTable("vehicle_management");

            // 审批流引擎模块
            modelBuilder.Entity<DefaultProcessDetail>().ToTable("default_process_detail");
            modelBuilder.Entity<Nodes>().ToTable("nodes");
            modelBuilder.Entity<Process>().ToTable("process");
            modelBuilder.Entity<ProcessDetail>().ToTable("process_detail");
            modelBuilder.Entity<Record>().ToTable("record");
            modelBuilder.Entity<Types>().ToTable("types");

            // 物资管理模块
            modelBuilder.Entity<Material>().ToTable("material");
            modelBuilder.Entity<MaterialStatistics>().ToTable("material_statistics");
            modelBuilder.Entity<MaterialWithdrawal>().ToTable("material_withdrawal");
            modelBuilder.Entity<SupplyPurchase>().ToTable("supply_purchase");
            modelBuilder.Entity<Domainwj.物资管理.Type>().ToTable("material_type");
            modelBuilder.Entity<WarehouseReceivingManagement>().ToTable("warehouse_receiving_management");

            // 系统管理模块
            modelBuilder.Entity<CompanyInfo>().ToTable("company_info");
            modelBuilder.Entity<Menus>().ToTable("menus");
            modelBuilder.Entity<Permissions>().ToTable("permissions");
            modelBuilder.Entity<RoleMenus>().ToTable("role_menus");
            modelBuilder.Entity<RolePermissions>().ToTable("role_permissions");
            modelBuilder.Entity<Roles>().ToTable("roles");
            modelBuilder.Entity<UserRoles>().ToTable("user_roles");
            modelBuilder.Entity<Users>().ToTable("users");

            // 结算管理模块
            modelBuilder.Entity<InboundOutboundInvoiceManagement>().ToTable("inbound_outbound_invoice_management");
            modelBuilder.Entity<PaymentManagemen>().ToTable("payment_management");
            modelBuilder.Entity<ReceivableFeeManagement>().ToTable("receivable_fee_management");

            // 车辆服务管理模块
            modelBuilder.Entity<AccidentRecord>().ToTable("accident_record");
            modelBuilder.Entity<BreakRulesAndRegulations>().ToTable("break_rules_and_regulations");
            modelBuilder.Entity<FeeRecord>().ToTable("fee_record");
            modelBuilder.Entity<MaintainRecord>().ToTable("maintain_record");
            modelBuilder.Entity<RepairRecord>().ToTable("repair_record");
            modelBuilder.Entity<TireRecord>().ToTable("tire_record");

            // 追踪管理模块
            modelBuilder.Entity<Order_info>().ToTable("order_info");
            modelBuilder.Entity<Route_info>().ToTable("route_info");
            modelBuilder.Entity<Shipping_status_log>().ToTable("shipping_status_log");
        }

        /// <summary>
        /// 配置字段约束
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        private void ConfigureFieldConstraints(ModelBuilder modelBuilder)
        {
            // 配置字符串字段长度限制
            ConfigureStringFields(modelBuilder);
            
            // 配置主键
            ConfigurePrimaryKeys(modelBuilder);
        }

        /// <summary>
        /// 配置字符串字段
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        private void ConfigureStringFields(ModelBuilder modelBuilder)
        {
            // 人员信息表字段配置
            modelBuilder.Entity<PersonInfo>()
                .Property(e => e.Name)
                .HasMaxLength(100);
            
            modelBuilder.Entity<PersonInfo>()
                .Property(e => e.PhoneNumber)
                .HasMaxLength(50);
            
            modelBuilder.Entity<PersonInfo>()
                .Property(e => e.Email)
                .HasMaxLength(100);

            // 部门表字段配置
            modelBuilder.Entity<Department>()
                .Property(e => e.DeptName)
                .HasMaxLength(50);

            // 职位表字段配置
            modelBuilder.Entity<Position>()
                .Property(e => e.PositionName)
                .HasMaxLength(50);
            
            modelBuilder.Entity<Position>()
                .Property(e => e.PositionAlias)
                .HasMaxLength(50);

            // 车辆管理表字段配置
            modelBuilder.Entity<VehicleManagement>()
                .Property(e => e.LicensePlateNumber)
                .HasMaxLength(20)
                .IsRequired();
            
            modelBuilder.Entity<VehicleManagement>()
                .Property(e => e.BrandandModel)
                .HasMaxLength(100)
                .IsRequired();

            // 货主信息表字段配置
            modelBuilder.Entity<CargoOwner>()
                .Property(e => e.OwnerName)
                .HasMaxLength(100)
                .IsRequired();
            
            modelBuilder.Entity<CargoOwner>()
                .Property(e => e.PhoneNumber)
                .HasMaxLength(20)
                .IsRequired();
        }

        /// <summary>
        /// 配置主键
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        private void ConfigurePrimaryKeys(ModelBuilder modelBuilder)
        {
            // 人员信息表主键配置
            modelBuilder.Entity<PersonInfo>()
                .HasKey(e => e.id);
            
            // 部门表主键配置
            modelBuilder.Entity<Department>()
                .HasKey(e => e.id);
            
            // 职位表主键配置
            modelBuilder.Entity<Position>()
                .HasKey(e => e.id);

            // 车辆管理表主键配置
            modelBuilder.Entity<VehicleManagement>()
                .HasKey(e => e.Id);

            // 货主信息表主键配置
            modelBuilder.Entity<CargoOwner>()
                .HasKey(e => e.Id);

            // 合同管理表主键配置
            modelBuilder.Entity<CargoOwnerContracts>()
                .HasKey(e => e.Id);
            
            modelBuilder.Entity<CarriageContracts>()
                .HasKey(e => e.Id);
            
            modelBuilder.Entity<GeneralContracts>()
                .HasKey(e => e.Id);
        }

        #endregion
        
    }
}
